import argopt
import os
import win32api
import win32con


def GetFileMd5(filename):
    import hashlib
    if not os.path.isfile(filename):
        return
    myHash = hashlib.md5()
    f = open(filename,'rb')
    while True:
        b = f.read(8096)
        if not b :
            break
        myHash.update(b)
    f.close()
    return myHash.hexdigest()


if __name__ == "__main__":
    data = [{
        'name': 'selected_function',
        'type': type(list),
        'default': [],
        'comment': 'selected functions to unit test'
    }, {
        'name': 'info_path',
        'type': type(str),
        'default': "",
        'comment': 'info path'
    }, {
        'name': 'testbook_path',
        'type': type(list),
        'default': [],
        'comment': 'testbook paths to unit test'
    }, {
        'name': 'help',
        'type': type(bool),
        'default': False,
        'comment': 'module construct tool'
    }]

    help_text = '''
     unittest_code_generator created by WPz.
       syntax:
             unittest_code_generator.py selected_function=
       example:
             python module_construct.py selected_function="['control_traction_initialize','Traction_Init','Traction_Control_10ms','Traction_Output_10ms']" output_path="C:/linde2020/lindeShare/c_project_static_anlyzer/src/output/output.json" testbook_path="C:/sandBox/kcpc/implement/simulation/workspace/src/control_traction"
     '''

    error, unknown, args, opts = argopt.parse(data, help_text)

    if not os.path.exists(opts['info_path']):
        print('info_path no exist')
        os.system('pause')
        exit(1)

    import json
    from openpyxl import load_workbook
    from openpyxl.styles import  PatternFill
    from openpyxl.comments import Comment
    import getpass

    fp = open(opts['info_path'])
    dic = json.loads(fp.read())
    

    integrated_dic = {}
    for info_unit in dic:
        func_name = info_unit['Function_Name']
        fail_num = info_unit['Fail_Num']
        para_dic = info_unit.popitem()
        if func_name not in integrated_dic.keys():
            integrated_dic.update({func_name:{fail_num:{}}})
        if fail_num not in integrated_dic[func_name].keys():
            integrated_dic[func_name].update({fail_num:{}})
        integrated_dic[func_name][fail_num].update({para_dic[0]:para_dic[1]})

    for function in opts['selected_function']:
        test_book_path = opts['testbook_path'] + '/' + function + '.xlsx'
        if not os.path.exists(test_book_path):
            print(function + ' test book no found!')
            continue
        ''' 
        test_book_path = test_book_path.replace('/','\\')
        out_file_path = opts['testbook_path']  + '\\' +  function + '.xlsx'
        # if wanna copy enable the codes
        xcopy_cmd = "echo Y| copy \""+ test_book_path + '\" \"'+ out_file_path + '\"'
        os.system(xcopy_cmd)
        '''
        
        wb = load_workbook(filename=test_book_path) 
        '''
        get sheet by index 0
        '''
        ws = wb[wb.get_sheet_names()[0]]
        if function in integrated_dic.keys():
            cell_row = 0
            start_row = 0
            cell_column = 1
            para_column = 2
            '''
            loop row
            '''
            while cell_row < ws.max_row:
                cell_row += 1
                if ws.cell(cell_row, cell_column).value == 'Test Cases':
                    start_row = cell_row + 1
                    break
            '''
            start to write loop column
            '''
            while cell_column <= ws.max_column:
                cell_row = start_row - 1
                '''
                judge if current header in info_out.json
                '''
                if ws.cell(cell_row, cell_column).value in integrated_dic[function].keys():
                    fail_num = ws.cell(cell_row, cell_column).value 
                    cell_row = start_row
                    '''
                    loop cell in this column
                    '''
                    while cell_row <= ws.max_row:
                        ws.cell(cell_row, cell_column).fill = PatternFill("solid", fgColor="FFFFFF")
                        ws.cell(cell_row, cell_column).comment = None
                        if ws.cell(cell_row, para_column-1).value[:5] != "Input" and   \
                            ws.cell(cell_row, para_column).value in integrated_dic[function][fail_num].keys():
                            writeComment ='result: ' + integrated_dic[function][fail_num][ws.cell(cell_row, para_column).value]
                            ws.cell(cell_row, cell_column).comment = Comment(writeComment, getpass.getuser())
                            # ws.cell(cell_row, cell_column, integrated_dic[function][fail_num][ws.cell(cell_row, para_column).value])
                            ws.cell(cell_row, cell_column).fill = PatternFill("solid", fgColor="D41212")
                        cell_row += 1
                else:
                    cell_row = start_row
                    while cell_row <= ws.max_row:
                        ws.cell(cell_row, cell_column).fill = PatternFill("solid", fgColor="FFFFFF")
                        ws.cell(cell_row, cell_column).comment = None
                        cell_row += 1

                cell_column += 1
            
            ws.cell(2,3,'TEST FAILED! '+ str(len(integrated_dic[function].keys())) + ' cases NG!')
            ws.cell(2,3).fill = PatternFill("solid", fgColor="D41212")
            ws.cell(2,4).fill = PatternFill("solid", fgColor="D41212")
            ws.cell(2,5).fill = PatternFill("solid", fgColor="D41212")
            ws.cell(2,6).fill = PatternFill("solid", fgColor="D41212")
            ws.cell(2,7).fill = PatternFill("solid", fgColor="D41212")
        else:
            ws.cell(2,3,'TEST PASSED')
            ws.cell(2,3).fill = PatternFill("solid", fgColor="FFFFFF")
            ws.cell(2,4).fill = PatternFill("solid", fgColor="FFFFFF")
            ws.cell(2,5).fill = PatternFill("solid", fgColor="FFFFFF")
            ws.cell(2,6).fill = PatternFill("solid", fgColor="FFFFFF")
            ws.cell(2,7).fill = PatternFill("solid", fgColor="FFFFFF")
            
            cell_row = 0
            start_row = 0
            cell_column = 1
            para_column = 2
            '''
            loop row
            '''
            while cell_row < ws.max_row:
                cell_row += 1
                if ws.cell(cell_row, cell_column).value == 'Test Cases':
                    start_row = cell_row + 1
                    break
            cell_column = 3
            '''
            start to write loop column
            '''
            while cell_column <= ws.max_column:
                cell_row = start_row
                while cell_row <= ws.max_row:
                    ws.cell(cell_row, cell_column).fill = PatternFill("solid", fgColor="FFFFFF")
                    ws.cell(cell_row, cell_column).comment = None
                    cell_row += 1
                cell_column += 1

        wb.save(test_book_path)
        md5 = GetFileMd5(test_book_path)
        file = open(test_book_path[:-4] + 'md5','w+')
        file.write(md5)
        file.close()


    
